//===================================================================================
// Microsoft patterns & practices
// Composite Application Guidance for Windows Presentation Foundation and Silverlight
//===================================================================================
// Copyright (c) Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===================================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===================================================================================
using System;
using System.Collections.Generic;
using Microsoft.Practices.Composite.Logging;
using Microsoft.Practices.Composite.Modularity;
using Microsoft.Practices.Composite.Tests.Mocks;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Microsoft.Practices.Composite.Tests.Modularity
{
	/// <summary>
	/// Summary description for ModuleInitializerFixture
	/// </summary>
	[TestClass]
	public class ModuleInitializerFixture
	{
		[TestMethod]
		[ExpectedException(typeof(ArgumentNullException))]
		public void NullLoggerThrows()
		{
			ModuleInitializer loader = new CustomModuleInitializerService(null);
		}

		[TestMethod]
		[ExpectedException(typeof(ModuleInitializeException))]
		public void InitializationExceptionsAreWrapped()
		{
			var moduleInfo = CreateModuleInfo(typeof(ExceptionThrowingModule));

			ModuleInitializer loader = new CustomModuleInitializerService(new MockLogger());

			loader.Initialize(moduleInfo);
		}


		[TestMethod]
		public void ShouldResolveModuleAndInitializeSingleModule()
		{
			var service = new CustomModuleInitializerService(new MockLogger());
			FirstTestModule.wasInitializedOnce = false;
			var info = CreateModuleInfo(typeof(FirstTestModule));
			service.Initialize(info);
			Assert.IsTrue(FirstTestModule.wasInitializedOnce);
		}


		[TestMethod]
		public void ShouldLogModuleInitializeErrorsAndContinueLoading()
		{
			var logger = new MockLogger();
			var service = new CustomModuleInitializerService(logger);
			var invalidModule = CreateModuleInfo(typeof(InvalidModule));

			Assert.IsFalse(service.HandleModuleInitializerrorCalled);
			service.Initialize(invalidModule);
			Assert.IsTrue(service.HandleModuleInitializerrorCalled);
		}

		[TestMethod]
		public void ShouldLogModuleInitializationError()
		{
			var logger = new MockLogger();
			var service = new ModuleInitializer(logger);
			ExceptionThrowingModule.wasInitializedOnce = false;
			var exceptionModule = CreateModuleInfo(typeof(ExceptionThrowingModule));

			try
			{
				service.Initialize(exceptionModule);
			}
			catch (ModuleInitializeException)
			{
			}

			Assert.IsNotNull(logger.LastMessage);
			StringAssert.Contains(logger.LastMessage, "ExceptionThrowingModule");
		}

		private static ModuleInfo CreateModuleInfo(Type type, params string[] dependsOn)
		{
			ModuleInfo moduleInfo = new ModuleInfo(type.Name, type.AssemblyQualifiedName);
			moduleInfo.DependsOn.AddRange(dependsOn);
			return moduleInfo;
		}

		public static class ModuleLoadTracker
		{
			public static readonly Stack<Type> ModuleLoadStack = new Stack<Type>();
		}

		public class FirstTestModule : IModule
		{
			public static bool wasInitializedOnce;

			public void Initialize()
			{
				wasInitializedOnce = true;
				ModuleLoadTracker.ModuleLoadStack.Push(GetType());
			}
		}

		public class SecondTestModule : IModule
		{
			public static bool wasInitializedOnce;
			public static long initializedOnTickCount;

			public void Initialize()
			{
				wasInitializedOnce = true;
				ModuleLoadTracker.ModuleLoadStack.Push(GetType());
			}
		}

		public class DependantModule : IModule
		{
			public static bool wasInitializedOnce;

			public void Initialize()
			{
				wasInitializedOnce = true;
				ModuleLoadTracker.ModuleLoadStack.Push(GetType());
			}
		}

		public class DependencyModule : IModule
		{
			public static bool wasInitializedOnce;
			public static long initializedOnTickCount;

			public void Initialize()
			{
				wasInitializedOnce = true;
				ModuleLoadTracker.ModuleLoadStack.Push(GetType());
			}
		}

		public class ExceptionThrowingModule : IModule
		{
			public static bool wasInitializedOnce;
			public static long initializedOnTickCount;

			public void Initialize()
			{
				throw new InvalidOperationException("Intialization can't be performed");
			}
		}

		public class InvalidModule { }

		public class CustomModuleInitializerService : ModuleInitializer
		{
			public bool HandleModuleInitializerrorCalled;

			public CustomModuleInitializerService(ILoggerFacade logger)
				: base(logger)
			{
			}

			public override void HandleModuleInitializationError(ModuleInfo moduleInfo, string assemblyName, Exception exception)
			{
				HandleModuleInitializerrorCalled = true;
			}

			protected override IModule CreateModule(string typeName)
			{
				return (IModule)Activator.CreateInstance(Type.GetType(typeName));
			}
		}

		public class Module1 : IModule { void IModule.Initialize() { } }
		public class Module2 : IModule { void IModule.Initialize() { } }
		public class Module3 : IModule { void IModule.Initialize() { } }
		public class Module4 : IModule { void IModule.Initialize() { } }
	}
}